Rust Note

Meow King January 06, 2024 Updated: January 06, 2024 #rust #note #collection
  1. function accept parameters similar type, like str, &str, String

    1. fn accept_all_strings(value: impl AsRef<str>)
      just need a string reference
    2. fn accept_all_strings(value: impl Into<String>)
      need an owned string
  2. use cloned method to solve some conversion error in iteration collection.

let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];

let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
  1. build a map using fold and entry
let map: BTreeMap<&str, u32> = BTreeMap::new();
self.rounds
    .iter()
    .fold(map, |mut acc, round| {
        for cube in round.iter() {
            acc.entry(cube.color)
                .and_modify(|v| {
                    *v = (*v).max(cube.amount);
                })
                .or_insert(cube.amount);
        }
        acc
    })
    .values()
    .product()
  1. Rust built-in traits: see Effective Rust - std-traits.
    Additional Note:

  2. FromStr trait: str's parse method.

  3. Difference between Borrow and AsRef

  4. Ownership

  5. into_iter and iter into_iter takes ownership, whilte iter not. So when origin is something like Vec<String>, then into_iter -> String (Item type), while iter -> &String; When &Vec<String>, then into_iter -> &String, while iter -> &&String

  6. Useful functions:

  7. HashSet: retain